package com.LeeCode;

/**
 * 二叉树的最近公共祖先
 */

public class Code236 {

    TreeNode ans;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return ans;
    }

    public boolean dfs(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return false;
        }

        boolean left = dfs(root.left, p, q);
        boolean right = dfs(root.right, p, q);
        boolean flag = root == p || root == q;
        if ((left && right) || (flag && (left || right)))
            ans = root;
        return left || right || flag;
    }
}
